package cn.javabb.bootdemo.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import tk.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @Author QINB imqinbao@163.com
 * @CreateDate 2019/1/10/010 17:48
 * @Since V1.0
 */
@Configuration
@MapperScan(basePackages = "cn.javabb.bootdemo.mapper.remote",sqlSessionFactoryRef = "remoteSqlSessionFactory")
public class RemoteDataSourceConfig {

    @Bean(name = "remoteDataSource")
    @Primary
    @ConfigurationProperties("spring.remote-datasource")
    public DataSource remoteDataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "remoteSqlSessionFactory")
    @Primary
    public SqlSessionFactory sqlSessionFactory(@Qualifier("remoteDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath*:mapper/remote/*.xml"));
        return sessionFactoryBean.getObject();
    }
    @Bean(name = "remoteTransactionManager")
    @Primary
    public DataSourceTransactionManager remoteTransactionManager(){
        return new DataSourceTransactionManager(remoteDataSource());
    }

}
